package com.netdisk.service.impl;
import com.netdisk.dto.UserActivityDTO;
import com.netdisk.dto.request.file.DeleteDTO;
import com.netdisk.dto.request.file.RestoreDTO;
import com.netdisk.dto.response.file.FileDTO;
import com.netdisk.entity.File;
import com.netdisk.entity.User;
import com.netdisk.mapper.FileMapper;
import com.netdisk.mapper.TrashMapper;
import com.netdisk.mapper.UserMapper;
import com.netdisk.service.TrashService;
import com.netdisk.service.UserActivityService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class TrashServiceImpl implements TrashService{

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private TrashMapper trashMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserActivityService userActivityService;

    /**
     * 获取回收站列表
     * @param userId
     * @return
     */
    @Override
    public List<FileDTO> getTrashListById(Integer userId) {
        List<FileDTO> trashList = new ArrayList<>();
        List<File> fileList = fileMapper.getFileListById(userId);
        for (int i = 0; i < fileList.size(); i++){
            if (fileList.get(i).getDeletedAt() != null){
                FileDTO fileDTO = new FileDTO();
                BeanUtils.copyProperties(fileList.get(i),fileDTO);
                trashList.add(fileDTO);
            }
        }
        return trashList;
    }

    /**
     * 获取回收站文件数
     * @param userId
     * @return
     */
    @Override
    public Integer getTrashCountById(Integer userId) {
        return this.getTrashListById(userId).size();
    }

    /**
     * 恢复文件
     * @param restoreDTO
     */
    @Override
    public void restoreFile(@RequestBody RestoreDTO restoreDTO) {
        trashMapper.delete(restoreDTO);
        fileMapper.restoreFile(restoreDTO.getFileId());

        File file = fileMapper.getFileById(restoreDTO.getFileId(),restoreDTO.getUserId());
        userActivityService.insertActivity(file, "从回收站恢复文件", "restore");
    }

    /**
     * 彻底删除文件
     * @param deleteDTO
     */
    @Override
    public void completelyDelete(@RequestBody DeleteDTO deleteDTO) {
        fileMapper.delete(deleteDTO);

        File file = fileMapper.getFileById(deleteDTO.getId(),deleteDTO.getUserId());
        userActivityService.insertActivity(file, "永久删除文件", "remove");
    }

    /**
     * 清空回收站
     * @param id
     */
    @Override
    public void trashClearById(Integer id){
        fileMapper.clear(id);
    }
}
